package com.aiyige;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.support.multidex.MultiDex;

import com.aiyige.base.log.CrashReportingTree;
import com.aiyige.configs.MyConfig;
import com.aiyige.im.NimSDKOptionConfig;
import com.aiyige.im.SessionHelper;
import com.aiyige.im.event.NimOnlineStateContentProvider;
import com.aiyige.jpush.TagAliasOperatorHelper;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppCommentUtils;
import com.aiyige.utils.crash.CrashHandler;
import com.aiyige.utils.network.NetBroadcastReceiver;
import com.aiyige.utils.prefs.Prefs;
import com.aiyige.utils.prefs.WuDaoPrefsHelper;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.mobstat.StatService;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.pingplusplus.android.Pingpp;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxTool;

import java.net.Proxy;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import timber.log.Timber;

/**
 * 支持LitePal数据库
 * Created by xiachao on 2017/8/9.
 */

public class MyApp extends Application {
    private Prefs prefs;

    private static Context context;

    private static MyApp instance;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        instance = this;

        initPlugIn();//初始化第三方插件
        PublishUtil.startPublish();
        //是否要在详情页弹出去评论app的对话框，默认需要
        AppCommentUtils.getInstance().setNeedShowAppComment(getPrefs().getBoolean(MyConfig.IS_SHOW_APP_COMMENT, true));
        //RxTool.init(this);// 由于RxTool在调用某些Activity的时候会弹出Toast，这里需要初始化，否则会报错崩溃。
    }

    private void initPlugIn() {
        //在这里先使用Timber.plant注册一个Tree，然后调用静态的.d .v 去使用
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new CrashReportingTree());
        }
        // PING++ debug模式开启
        Pingpp.DEBUG = BuildConfig.DEBUG;

        // 百度统计调试开关，正式版本请关闭，以免影响性能
        StatService.setDebugOn(BuildConfig.DEBUG);
        CrashHandler.getInstance().init(this, "/eig/log/");
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化

        // UMeng
//        Config.DEBUG = true;
//        QueuedWork.isUseThreadPool = false;
//        UMShareAPI.get(this);
        // UMeng
        UMConfigure.init(this, "59f03f218f4a9d112d000043"
                , "aiyige", UMConfigure.DEVICE_TYPE_PHONE, "");
        initFileDownloader();
        initBugly();
        initJPush();
        initWX();
        initX5();
        initRxTool();
        // 初始化云信SDK
        NIMClient.init(this, loginInfo(), NimSDKOptionConfig.getSDKOptions(MyApp.getAppContext()));
        initNetworkListener();
//        NIMClient.initSDK();
//
        if (NIMUtil.isMainProcess(this)) {
            // 在主进程中初始化UI组件，判断所属进程方法请参见demo源码。
            initUIKit();
        }
    }

    // 在Android 7.0之静态注册广播的方式被取消了，所以我们这里采用动态注册的方式
    private void initNetworkListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //实例化IntentFilter对象
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            NetBroadcastReceiver netBroadcastReceiver = new NetBroadcastReceiver();
            //注册广播接收
            registerReceiver(netBroadcastReceiver, filter);
        }
    }

    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());
        SessionHelper.init();


        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
//        NimUIKit.setLocationProvider(new NimDemoLocationProvider());

        // IM 会话窗口的定制初始化。
//        SessionHelper.init();

        // 聊天室聊天窗口的定制初始化。
//        ChatRoomSessionHelper.init();

        // 通讯录列表定制初始化
//        ContactHelper.init();

        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
//        NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());

        NimUIKit.setOnlineStateContentProvider(new NimOnlineStateContentProvider());
    }

    private LoginInfo loginInfo() {
        if (AccountUtil.getIMbackup() != null) {
            return new LoginInfo(AccountUtil.getIMbackup().getAccid(),AccountUtil.getIMbackup().getToken());
        } else {
            return null;
        }
    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = MyConfig.AIYIGE_ROOT_DIR +  "/nim";
        return options;
    }


    private void initRxTool() {
        RxTool.init(this);
    }

    private void initX5() {
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {

            }

            @Override
            public void onViewInitFinished(boolean b) {

            }
        });
    }

    private void initWX() {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, null);
        iwxapi.registerApp(BuildConfig.WEIXIN_ID);
    }

    private void initJPush() {
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);
        if (BuildConfig.DEBUG) {
            Set<String> tagSet = new HashSet<>();
            tagSet.add(TagAliasOperatorHelper.TAG_DEBUG);
            TagAliasOperatorHelper.getInstance().addTag(this, tagSet);
        }
        if (!ConfigUltis.isEnableMessagePush()) {
            JPushInterface.stopPush(this);
        }
        if (AccountUtil.isLogin()) {
            TagAliasOperatorHelper.getInstance().registerLoginTagAndAlias(MyApp.getAppContext(), AccountUtil.getCurrentUser());
        }
    }

    private void initBugly() {
//        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this); //...在这里设置strategy的属性，在bugly初始化时传入
//        CrashReport.initCrashReport(this, "758e40ddce", true, strategy);
//        strategy.setAppChannel();
//        strategy.setAppV
//        Bugly.init(this, "758e40ddce", true);
//        if (BuildConfig.enableBugly) {
//            Bugly.init(this, BuildConfig.BUGLY_APPID, false);
//        }
        Bugly.init(this, BuildConfig.BUGLY_APPID, false);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);
        // 安装tinker
        Beta.installTinker();
    }


    {

        PlatformConfig.setWeixin(BuildConfig.WEIXIN_ID, BuildConfig.WEIXIN_SECRET);
        PlatformConfig.setSinaWeibo(BuildConfig.SINA_WEIBO_KEY, BuildConfig.SINA_WEIBO_SECRET, BuildConfig.SINA_WEIBO_REDIRECTURL);
        PlatformConfig.setQQZone(BuildConfig.QQ_ZONE_ID, BuildConfig.QQ_ZONE_KEY);
//        PlatformConfig.setAlipay(BuildConfig.ALIPAY_ID);
    }

    public void initFileDownloader() {
        // just for open the log in this demo project.
        FileDownloadLog.NEED_LOG = BuildConfig.DEBUG;

        /**
         * just for cache Application's Context, and ':filedownloader' progress will NOT be launched
         * by below code, so please do not worry about performance.
         * @see FileDownloader#init(Context)
         */
        FileDownloader.setupOnApplicationOnCreate(this)
                .connectionCreator(new FileDownloadUrlConnection
                        .Creator(new FileDownloadUrlConnection.Configuration()
                        .connectTimeout(15_000) // set connection timeout.
                        .readTimeout(15_000) // set read timeout.
                        .proxy(Proxy.NO_PROXY) // set proxy
                ))
                .commit();
    }

    public static Context getAppContext() {
        return context;
    }

    public static MyApp getInstance() {
        return instance;
    }

    public synchronized Prefs getPrefs() {
        if (prefs == null) {
            prefs = new WuDaoPrefsHelper(getApplicationContext()).getPrefs();
        }
        return prefs;
    }

    public void quit() {
        RxActivityTool.AppExit(this);
    }

    public String getStringById(int stringId) {
        return this.getString(stringId);
    }

}
